
package cn.jy.nvr.ftp1;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ftpSenderFile {

	public static int				Socket_Buf_Size				= 256 * 1024;

	public static int				Server_Connect_TimeOut		= 30000;
	public static int				Client_Connect_TimeOut		= 5 * 60000;

	public static int				Server_Connect_SoLinger		= 0;
	public static int				Client_Connect_SoLinger		= 2;

	private static final String		RealDateTimeFormatString	= "yyyy-MM-dd HH:mm:ss:SSS";
	private static SimpleDateFormat	RealDateTimeFormat			= new SimpleDateFormat(RealDateTimeFormatString);

	public static String toRealDateText(Date date) {
		synchronized (RealDateTimeFormat) {
			if (date == null) {
				return "";
			}
			return RealDateTimeFormat.format(date);
		}
	}

	private String	host;
	private int		port;

	public ftpSenderFile(String host, int port) {
		this.setHost(host);
		this.setPort(port);
	}

	public String send(String localFilePath, String remoteFilePath) throws IOException {
		File srcFile = new File(localFilePath);
		if (!(srcFile.isFile() || srcFile.isDirectory()))
			System.out.println("不能打开文件");
		if (!srcFile.canRead())
			System.out.println("不能读取文件");;

		InetAddress address = InetAddress.getByName(getHost());
		Socket s;
		int idx = 0;
		while (true) {
			try {
				s = new Socket();
				s.setReuseAddress(true);
				s.setKeepAlive(true);
				s.setTcpNoDelay(true);
				s.setSoTimeout(Client_Connect_TimeOut);
				s.setSoLinger(false, Client_Connect_SoLinger);
				s.setReceiveBufferSize(Socket_Buf_Size + 1024);
				s.setSendBufferSize(Socket_Buf_Size + 1024);
				s.setPerformancePreferences(0, 1, 2);
				s.connect(new InetSocketAddress(address, port));
				break;
			} catch (IOException e) {
			}
			s = null;
			idx++;
			if (idx > 0) {
				System.out.println("连接失败");;
			}
			synchronized (this) {
				try {
					this.wait(500);
				} catch (InterruptedException e) {
				}
			}
		}
		try {
			DataInputStream in = new DataInputStream(s.getInputStream());
			try {
				DataOutputStream out = new DataOutputStream(s.getOutputStream());
				try {
					//文件信息
					byte[] filePathBytes = null;
					try {
						filePathBytes = remoteFilePath.getBytes("GB2312");
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}

					int length = filePathBytes.length;
					System.out.println(length+"文件信息长度");
					out.writeInt(length);
					out.flush();
					int pos = 0;
					int count;
					while (pos < length) {
						count = length - pos;
						if (count > Socket_Buf_Size) {
							count = Socket_Buf_Size;
						}
						out.write(filePathBytes, pos, count);
						out.flush();
						pos += count;
					}

					// 文件时间
					byte[] fileDateBytes = toRealDateText(new Date(srcFile.lastModified())).getBytes();

					length = fileDateBytes.length;
					System.out.println("文件时间长度"+length);
					out.writeInt(length);
					out.flush();
					pos = 0;
					while (pos < length) {
						count = length - pos;
						if (count > Socket_Buf_Size) {
							count = Socket_Buf_Size;
						}
						out.write(fileDateBytes, pos, count);
						out.flush();
						pos += count;
					}

					int res_code = in.readInt();
					System.out.println(res_code+"返回码");
					if (res_code == 0xFB) {
						int end_code = 0xFFAA;
						out.writeInt(end_code);
						out.flush();
						return new String("");
					}

					if (res_code != 0xFC) {
						System.out.println("系统错误");
					}

					//文件数据
					length = (int) srcFile.length();
					System.out.println("文件数据长度"+length);
					out.writeInt(length);
					out.flush();
					
					byte[] bodyData = new byte[Socket_Buf_Size];

					java.io.FileInputStream fileIn = new java.io.FileInputStream(srcFile);
					try {
						pos = 0;
						while (pos < length) {
							count = length - pos;
							if (count > Socket_Buf_Size) {
								count = Socket_Buf_Size;
							}
							if (count < 1)
								break;
							fileIn.read(bodyData, 0, count);
							out.write(bodyData, 0, count);
							out.flush();
							pos += count;
						}
					} finally {
						fileIn.close();
					}

					// 反馈结果
					res_code = in.readInt();
					System.out.println(res_code+"返回结果码");
					length = in.readInt();
					System.out.println(length+"返回结果长度");
					byte[] res = null;
					int end_code = 0xFFAA;
					if (length > 0) {
						res = new byte[length];
						pos = 0;
						while (pos < length) {
							count = length - pos;
							if (count > Socket_Buf_Size) {
								count = Socket_Buf_Size;
							}
							count = in.read(res, pos, count);
							pos += count;
						}
					}
					out.writeInt(end_code);
					out.flush();
					if (res_code != 0) {
						if (res == null)
							System.out.println("系统错误");;
						System.out.println(new String(res, "GB2312"));
					}
					if (res == null)
						return new String("");
					return new String(res, "GB2312");
				} finally {
					out.close();
				}
			} finally {
				in.close();
			}
		} finally {
			s.close();
		}
	}

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

}